﻿using System;
using System.Collections.Generic;
using System.Linq;
using TestOnlineProject.Models.Entities;

namespace TestOnlineProject.Models.DataAccess
{
    public class ParticipantDAO
    {
        private TestOnlineDBEntities db = new TestOnlineDBEntities();

        public List<Participant> SelectBySubjectId(int subjectId)
        {
            var participants = db.Participants.Where(p => p.SubjectId == subjectId).ToList();
            return participants;
        }

        public List<Participant> SelectByUserId(int userId)
        {
            var participants = db.Participants.Where(p => p.UserId == userId && p.IsActivated).ToList();
            return participants;
        }

        public Participant SelectByUserIdSubjectId(int userId, int subjectId)
        {
            var existParticipant = db.Participants.FirstOrDefault(p => (p.UserId == userId && p.SubjectId == subjectId));
            return existParticipant;
        }

        public int Insert(Participant participant)
        {
            try
            {
                db.Participants.AddObject(participant);
                int result = db.SaveChanges();
                return result;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public int Update(Participant participant)
        {
            int result = db.SaveChanges();
            return result;
        }

        public int Delete(int subjectId, int userId)
        {
            var participant = db.Participants.Where(p => p.SubjectId == subjectId && p.UserId == userId).FirstOrDefault();
            db.Participants.DeleteObject(participant);
            int result = db.SaveChanges();
            return result;
        }

        public int Delete(int userId)
        {
            var participants = db.Participants.Where(x => x.UserId == userId);
            foreach (var participant in participants)
            {
                db.Participants.DeleteObject(participant);
            }
            var result = db.SaveChanges();
            return result;
        }
    }
}